package com.shenzhen.horselive.wxapi;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.JsonObject;
import com.lljjcoder.style.citylist.Toast.ToastUtils;
import com.shenzhen.horselive.Constants;
import com.shenzhen.horselive.MainActivity;
import com.shenzhen.horselive.User;
import com.shenzhen.horselive.api.ApiFactory;
import com.shenzhen.horselive.beans.IsBindBean;
import com.shenzhen.horselive.network.SchedulersCompat;
import com.shenzhen.horselive.presenter.BaseView;
import com.shenzhen.horselive.presenter.ViewObserver;
import com.shenzhen.horselive.ui.activity.BindPhoneActivity;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler, BaseView {
    private IWXAPI api;
    private  static BaseResp mBaseResp = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getSupportActionBar().hide();
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        api = WXAPIFactory.createWXAPI(this, Constants.WECHAT_APPID,false);
        api.handleIntent(getIntent(), this);
    }

    @Override
    public void onReq(BaseReq baseReq) {
//      finish();
    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    @Override
    public void onResp(BaseResp resp) {

        if (resp.getType()== ConstantsAPI.COMMAND_PAY_BY_WX)
        {
            //支付
            finish();
        }
        else if (resp.getType()==ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX)
        {
            //分享
            if (resp.errCode==BaseResp.ErrCode.ERR_OK)
            {
                Toast.makeText(this, "分享成功", Toast.LENGTH_LONG).show();

            }else
            {
                Toast.makeText(this, "分享取消", Toast.LENGTH_LONG).show();

            }
            finish();
        }
        else if (resp.getType()==ConstantsAPI.COMMAND_SENDAUTH)
        {

            String result = "";
            if (resp != null) {
                this.mBaseResp = resp;
            }
            switch(resp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    if (resp instanceof SendAuth.Resp)
                    {
                        //登录的回调
                        String code = ((SendAuth.Resp) resp).code;
                        //获取accesstoken
                        if (code!=null)
                            getAccessToken(code);
                    }
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    result = "发送取消";
                    Toast.makeText(this, result, Toast.LENGTH_LONG).show();
                    finish();
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED:
                    result = "发送被拒绝";
                    Toast.makeText(this, result, Toast.LENGTH_LONG).show();
                    finish();
                    break;
                default:
                    result = "发送返回";
                    Toast.makeText(this, result, Toast.LENGTH_LONG).show();
                    finish();
                    break;
            }


        }






    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
        finish();
    }


    ProgressDialog  mProgressDialog ;
    private void createProgressDialog() {
        mProgressDialog=new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//转盘
        mProgressDialog.setCancelable(false);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setTitle("提示");
        mProgressDialog.setMessage("登录中，请稍后");
        mProgressDialog.show();
    }




    private void getAccessToken(String code) {
        createProgressDialog();
        ApiFactory.getApiService().isBindPhone(code)
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new ViewObserver<IsBindBean>(this) {
                    @Override
                    protected void onNextInActive(IsBindBean bean) {
                        mProgressDialog.dismiss();
                      if ("NOT_REGISTERED".equals(bean.getErrCode()))
                      {
                          //未注册
                          User.get().storeMyInfo(bean.getData());
                         startActivity(new Intent(WXEntryActivity.this, BindPhoneActivity.class));
                      }
                      else if (bean.getData()!=null)
                      {
                          //已经注册过的
                          User.get().storeMyInfo(bean.getData());
                          User.get().setLogin(true);
                          startActivity(new Intent(WXEntryActivity.this, MainActivity.class));

                      }
                      else
                      {
                          Toast.makeText(WXEntryActivity.this,bean.getErrMessage(),Toast.LENGTH_SHORT).show();
                      }
                      //关闭
                      finish();
                    }
                });
    }


    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showError(Throwable e) {

    }

    @Override
    public boolean isActive() {
        return true;
    }
}
